package com.example.udpsender;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.InetAddress;
import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.net.InetAddress;
import java.net.Inet4Address;
import android.os.AsyncTask;

public final class UdpSenderTask extends AsyncTask<JoyStickEnum, Void, Void> {
	
private 
	DatagramSocket sock;
	final String dstAddr = "192.168.0.100";
	final String dataUpClicked = "UP Clicked";
	int	   dstPort = 55991;
	int	   localPort = 55991;

	@Override
	protected void onPreExecute()
	{
		try{
		sock = new DatagramSocket(localPort);
		}
		catch (SocketException e1) {
			e1.printStackTrace();
	    }
	}
	
	@Override
	protected Void doInBackground(JoyStickEnum... params) {
		 InetAddress dest;
		 try
		 {
		 dest = Inet4Address.getByName(dstAddr);
	     //DatagramSocket socket = new DatagramSocket();
		 sock.connect(new InetSocketAddress(dest,dstPort));
		 
		 byte[] message;
		 if(params.length < 1)
			 return null;
		 switch(params[0])
		 {
		 case BUTTON_INDEX_UP:
		 {
			message = "UP".getBytes();
		 }break;
		 case BUTTON_INDEX_DOWN:
		 {
			message = "DOWN".getBytes();
		 }break;
		 case BUTTON_INDEX_LEFT:
		 {
			message = "LEFT".getBytes();
		 }break;
		 case BUTTON_INDEX_RIGHT:
		 {
			message = "RIGHT".getBytes();
		 }break;
		 case BUTTON_INDEX_ACTION_A:
		 {
			message = "A".getBytes();
		 }break;
		 case BUTTON_INDEX_ACTION_B:
		 {
			message = "B".getBytes();
		 }break;
		 case BUTTON_INDEX_ACTION_Y_UP:
		 {

				message = "Y,UP".getBytes();
		 }break;
		 case BUTTON_INDEX_ACTION_Y_DOWN:
		 {

				message = "Y,DOWN".getBytes();
		 }break;
		 default:
		 {
			message = "NULL".getBytes();
		 }break;
		 }
		 DatagramPacket packet = new DatagramPacket(message, message.length,dest,dstPort);
		 sock.send(packet);
		 
		 sock.close();
		 }
		 catch (IOException e)
		 {
				e.printStackTrace();
		 }
		return null;
	}

}
